<?php

class Lib_Repair_Base_ZR extends Lib_Repair_Base_Tool
{

    private static function getConfig($key)
    {
        return Lib_Repair_Config::getConfig('ZR')[$key];
    }
    //获取请求头
    private static function getHeader($need_token = 0){

        $header = [
            'Content-Type:application/json;charset=utf-8',
            'X-TraceID:'.self::getNonce(),
        ];
        if($need_token == 1){
            $token = self::getToken();
            $header[] = "Authorization:Bearer {$token}";
        }
        return $header;
    }

    //curl 请求
    public static function curlPost($api,$params = [],$timeout = 30)
    {
        $url = self::getConfig('api').$api;
        $logs = ' request_url='.$url;
        if($api == '/v1/api/auth'){
            $header = self::getHeader();
        }else{
            $header = self::getHeader(1);
        }
        $logs .= " request_header=".json_encode($header);
        $reqestData = json_encode($params);
        $logs .= ' request_data= '.$reqestData;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $reqestData);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $log = array();
        $res = curl_exec($ch);
        $log['errno'] = curl_errno($ch);
        $log['error'] = curl_error($ch);
        $log['httpcode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($log['errno'] !== 0) {
            curl_close($ch);
            $result['code'] = 400;
            $result['message'] = 'request fail errno'.$log['errno'];
            Func_Log::write('curl','curl_response401', $logs.'response : '.json_encode($log));
            return $result;
        }
        curl_close($ch);
        $logs .= 'RETURN : '.$res;
        $res = json_decode($res, true);
        if (!is_array($res) || count($res) <= 0) {
            //返回值错误日志
            $result['code'] = 400;
            $result['message'] = 'Inlegal json response';
            $log['message'] = 'Inlegal json response';
            Func_Log::write('curl', 'curl_response401', $logs.'response : '.json_encode($log));
            return $result;
        }
        Func_Log::write('curl', 'curl_response', $logs);
        return $res;
    }

    // get请求
    public static function curlGet($api,$params = [],$timeout = 30)
    {
        $url = self::getConfig('api').$api;
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        $logs = ' request_url='.$url;
        $header = self::getHeader(1);
        $logs .= " request_header=".json_encode($header);
        $reqestData = json_encode($params);
        $logs .= ' request_data= '.$reqestData;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $log = array();
        $res = curl_exec($ch);
        $log['errno'] = curl_errno($ch);
        $log['error'] = curl_error($ch);
        $log['httpcode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($log['errno'] !== 0) {
            curl_close($ch);
            $result['code'] = 400;
            $result['message'] = 'request fail errno'.$log['errno'];
            Func_Log::write('curl','curl_response401', $logs.'response : '.json_encode($log));
            return $result;
        }
        curl_close($ch);
        $logs .= 'RETURN : '.$res;
        Func_Log::write('curl', 'curl_response', $logs.'response : '.json_encode($log));
        $res = json_decode($res, true);
        if (!is_array($res) || count($res) <= 0) {
            //返回值错误日志
            $result['code'] = 400;
            $result['message'] = 'Inlegal json response';
            $log['message'] = 'Inlegal json response';
            Func_Log::write('curl', 'curl_response401', $logs.'response : '.json_encode($log));
            return $result;
        }
        Func_Log::write('curl', 'curl_response', $logs.'response : '.json_encode($log));
        return $res;
    }



    //建立请求数据
    public function buildData($data){
        $backtrace = debug_backtrace();
        array_shift($backtrace);
        $type = $backtrace[0]['function'];
        $post_data = [];
        if(empty($data)){
            return $post_data;
        }
        switch ($type)
        {
            case 'repair':
                foreach ($data['repairData'] as $k => $v){
                    if(Lib_Repair_Base_Tool::checkData($v,['repairName','sha256idCard'])){
                        $post_data[$k]['name']  = hash("sha256", $v['repairName']);
                        $post_data[$k]['idCard'] =  $v['sha256idCard'];
                        $post_data[$k]['phone'] = empty($v['knownMobile']) ? '': $v['knownMobile'];
                    }
                }
                $post_data = ['batchName'=>$data['businessData']['rerairId'],'provideType'=>$data['businessData']['repairType'] == 1 ? '3' : '5' ,'data'=>$post_data];
                break;
            case 'getRepairResult':
                if(Lib_Repair_Base_Tool::checkData($data,['batchNo'])){
                    $post_data['batchID'] = $data['batchNo'];
                }
                break;
            case 'binding':
                if(Lib_Repair_Base_Tool::checkData($data,['resultId','seatNumber'])){
                    $post_data['repairPhoneID'] = $data['resultId'];
                    $post_data['callNo'] = $data['seatNumber'];
                }
                break;
            case 'unbinding':
                if(Lib_Repair_Base_Tool::checkData($data,['repairPhoneID','bindId','telx'])){
                    $post_data['repairPhoneID'] = $data['repairPhoneID'];
                    $post_data['bindId'] = $data['bindId'];
                    $post_data['telx'] = $data['telx'];
                }
                break;
        }
        return empty($post_data) ? [] : $post_data;
    }

    //返回并记录日志
    public function returnData($code=200,$message='success',$data=[]){
            $backtrace = debug_backtrace();
            array_shift($backtrace);
            $type = $backtrace[0]['function'];
            $returnData = [
                'code' => $code,
                'message' => $message,
                'data' => $data,
        ];
        Func_Log::write('request','liantong'.'---'.$type.' --- '.$message, json_encode($returnData));
        return  $returnData;
    }

    public static function getToken(){
        $authorization =  Lib_Redis_String::get('ZR-TOKEN');
        if($authorization){
            return $authorization;
        }
        $res = self::curlPost('/v1/api/auth',
            [
               'username'=> self::getConfig('username'),
               'password'=> self::getConfig('password'),
            ]
        );
        if($res['code'] == 200){
            Lib_Redis_String::setex('ZR-TOKEN',7198,$res['data']);
            return $res['data'];
        }else{
            throw new Exception('获取token失败',4005);
        }

    }
}